package cc.smarnet.caihou.phone.deliver;

import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cc.smarnet.caihou.IPConfig;
import cc.smarnet.caihou.LoginActivity;
import cc.smarnet.caihou.R;

import cc.smarnet.caihou.entity.Deliver;
import cc.smarnet.caihou.entity.DeliverVariety;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * 出库品种信息详情的Activity
 * */
public class DeliverVarietyDetailActivity extends AppCompatActivity {
    private ImageButton imageButton;
    private Spinner classesSpinner;//等级
    private Spinner flowerPoleLengthSpinner;//花杆长度
    private EditText numberEditText;//数量
    private Spinner packingSpecificationsSpinner;//规格
    private Spinner varietySpinner;//品种
    private TextView varietyCodeTextView;//品种编码;
    private ProgressBar progressBar;
    private Button editButton;
    private Button saveButton;
    private Button deleteButton;

    Deliver deliver;
    DeliverVariety deliverVariety;

    private String classes; // 等级
    private String flowerPoleLength; // 花杆长度
    private String number; // 数量(扎)
    private String packingSpecifications; // 规格
    private String variety;//品种
    private String varietyCode; // 品种编码

    private String token;

    int classesPosition = 0;//默认等级在接口返回的等级列表的位置
    int flowerPoleLengthPosition = 0;//默认花杆长度在接口返回的花杆长度列表的位置
    int packingSpecificationsPosition = 0;//默认打包规格在接口返回的打包规格列表的位置
    int varietyPosition = 0;//默认品种在接口返回的品种列表的位置


    List<String> classesList = new ArrayList<>();
    List<String> flowerPoleLengthList = new ArrayList<>();
    List<String> packingSpecificationsList = new ArrayList<>();
    List<String> varietyList = new ArrayList<>();
    List<String> varietyCodeList = new ArrayList<>();

    int mYear, mMonth, mDay;

    private final String basePath = "/sys/dict/getDictItems";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_deliver_variety_detail);

        getSupportActionBar().hide();//隐藏标题栏

        initViews();
        //获取从DeliverDetailActivity中传过来的值
        deliver = (Deliver) getIntent().getSerializableExtra("deliverDetail");
        deliverVariety = (DeliverVariety) getIntent().getSerializableExtra("deliverVarietyDetail");
        // 如果出库状态是-1（待出库），那么删除和编辑按钮可见，否则不可见
        if(deliver.getState()==-1){
            deleteButton.setVisibility(View.VISIBLE);
            editButton.setVisibility(View.VISIBLE);
        }else {
            deleteButton.setVisibility(View.GONE);
            editButton.setVisibility(View.GONE);
        }

        classes=deliverVariety.getClasses();
        flowerPoleLength=deliverVariety.getFlowerPoleLength();
        number=deliverVariety.getNumber();
        packingSpecifications=deliverVariety.getPackingSpecifications();
        variety=deliverVariety.getVariety();
        varietyCode=deliverVariety.getVarietyCode();


        numberEditText.setText(number);//设置默认的数量
        varietyCodeTextView.setText(varietyCode);//设置默认的品种编码

        setDisEnabled();
        getToken();
        getVariety();//获取采收品种
        getPackingSpecifications();//获取打包规格
        getFlowerPoleLength();//获取花杆长度
        getClasses();//获取等级


        getDate();// 获取当前的日期

        //点击编辑按钮的监听
        editButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editButton.setVisibility(View.GONE);
                saveButton.setVisibility(View.VISIBLE);
                setEnabled();
            }
        });

        //点击保存按钮的监听
        saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 获取数量
                if (numberEditText.getText().toString().equals("")) {
                    AlertDialog alertDialog = new AlertDialog.Builder(DeliverVarietyDetailActivity.this).create();
                    alertDialog.setMessage("请输入入库数量！");
                    alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
                    alertDialog.show();
                    return;
                } else {
                    number = numberEditText.getText().toString();
                }

                // 保存入库信息
                save();
            }
        });

        //点击删除按钮的监听
        deleteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog alertDialog = new AlertDialog.Builder(DeliverVarietyDetailActivity.this).create();
                alertDialog.setMessage("是否确认删除");
                alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        delete();
                    }
                });
                alertDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                    }
                });
                alertDialog.setCanceledOnTouchOutside(false);
                alertDialog.show();
            }
        });

        // 点击返回按钮的监听
        imageButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    public void initViews() {
        imageButton = findViewById(R.id.deliver_variety_detail_return);
        classesSpinner = findViewById(R.id.deliver_variety_detail_classes_spinner);
        flowerPoleLengthSpinner = findViewById(R.id.deliver_variety_detail_flowerPoleLength_spinner);
        packingSpecificationsSpinner = findViewById(R.id.deliver_variety_detail_packingSpecifications_spinner);
        varietySpinner = findViewById(R.id.deliver_variety_detail_variety_spinner);
        varietyCodeTextView = findViewById(R.id.deliver_variety_detail_varietyCode_textView);
        numberEditText = findViewById(R.id.deliver_variety_detail_number_editText);
        progressBar = findViewById(R.id.deliver_variety_detail_progressBar);
        editButton = findViewById(R.id.deliver_variety_detail_edit_button);
        saveButton = findViewById(R.id.deliver_variety_detail_save_button);
        deleteButton = findViewById(R.id.deliver_variety_detail_delete_button);
    }

    // 设置各控件不可用
    public void setDisEnabled() {
        classesSpinner.setEnabled(false);
        flowerPoleLengthSpinner.setEnabled(false);
        packingSpecificationsSpinner.setEnabled(false);
        varietySpinner.setEnabled(false);
        //varietyCodeTextView.setEnabled(false);
        numberEditText.setEnabled(false);
    }

    // 设置各控件可用
    public void setEnabled() {
        classesSpinner.setEnabled(true);
        flowerPoleLengthSpinner.setEnabled(true);
        packingSpecificationsSpinner.setEnabled(true);
        varietySpinner.setEnabled(true);
        //varietyCodeTextView.setEnabled(true);
        numberEditText.setEnabled(true);
    }

    public void getToken() {
        SharedPreferences sp = getSharedPreferences("userInfo", MODE_PRIVATE);
        token = sp.getString("token", null);
    }

    // 获取品种
    public void getVariety() {
        progressBar.setVisibility(View.VISIBLE);
        String url = IPConfig.baseUrl + "/flower/flowerVariety/list";
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progressBar.setVisibility(View.GONE);
                        Toast.makeText(DeliverVarietyDetailActivity.this, "Token失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(DeliverVarietyDetailActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        progressBar.setVisibility(View.GONE);
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            JSONArray jsonArray = JSON.parseArray(result);

                            for (int i = 0; i < jsonArray.size(); i++) {
                                JSONObject jsonObj = jsonArray.getJSONObject(i);
                                String name = jsonObj.getString("name");
                                varietyList.add(name);

                                // 获取品种编码
                                String code=jsonObj.getString("code");
                                varietyCodeList.add(code);

                                if (deliverVariety.getVariety().equals(name)){
                                    varietyPosition=i;
                                }
                            }

                            if (varietyList.size() > 0) {
                                varietySpinner();
                            }
                        }
                    }
                });
    }

    // 获取打包规格
    public void getPackingSpecifications() {
        progressBar.setVisibility(View.VISIBLE);
        String url = IPConfig.baseUrl + basePath + "/planting_packing_specifications";
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progressBar.setVisibility(View.GONE);
                        Toast.makeText(DeliverVarietyDetailActivity.this, "Token失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(DeliverVarietyDetailActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        progressBar.setVisibility(View.GONE);
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            JSONArray jsonArray = JSON.parseArray(result);

                            for (int i = 0; i < jsonArray.size(); i++) {
                                JSONObject jsonObj = jsonArray.getJSONObject(i);
                                String name = jsonObj.getString("text");
                                packingSpecificationsList.add(name);

                                if (deliverVariety.getPackingSpecifications().equals(name)){
                                    packingSpecificationsPosition=i;
                                }
                            }

                            if (packingSpecificationsList.size() > 0) {
                                packingSpecificationsSpinner();
                            }
                        }
                    }
                });
    }

    // 获取花杆长度
    public void getFlowerPoleLength() {
        progressBar.setVisibility(View.VISIBLE);
        String url = IPConfig.baseUrl + basePath + "/planting_flower_pole";
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progressBar.setVisibility(View.GONE);
                        Toast.makeText(DeliverVarietyDetailActivity.this, "Token失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(DeliverVarietyDetailActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        progressBar.setVisibility(View.GONE);
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            JSONArray jsonArray = JSON.parseArray(result);

                            for (int i = 0; i < jsonArray.size(); i++) {
                                JSONObject jsonObj = jsonArray.getJSONObject(i);
                                String name = jsonObj.getString("text");
                                flowerPoleLengthList.add(name);

                                if (deliverVariety.getFlowerPoleLength().equals(name)){
                                    flowerPoleLengthPosition=i;
                                }
                            }

                            if (flowerPoleLengthList.size() > 0) {
                                flowerPoleLengthSpinner();
                            }
                        }
                    }
                });
    }

    // 获取等级
    public void getClasses() {
        progressBar.setVisibility(View.VISIBLE);
        String url = IPConfig.baseUrl + basePath + "/planting_flower_level";
        OkHttpUtils
                .get()
                .addHeader("X-Access-Token", token)
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progressBar.setVisibility(View.GONE);
                        Toast.makeText(DeliverVarietyDetailActivity.this, "Token失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(DeliverVarietyDetailActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        progressBar.setVisibility(View.GONE);
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            String result = JSON.parseObject(response).getString("result");
                            JSONArray jsonArray = JSON.parseArray(result);

                            for (int i = 0; i < jsonArray.size(); i++) {
                                JSONObject jsonObj = jsonArray.getJSONObject(i);
                                String name = jsonObj.getString("text");
                                classesList.add(name);

                                if (deliverVariety.getClasses().equals(name)){
                                    classesPosition=i;
                                }
                            }

                            if (classesList.size() > 0) {
                                classes = classesList.get(0);// 设置默认的打包规格
                                classesSpinner();
                            }
                        }
                    }
                });
    }

    //品种的spinner
    public void varietySpinner() {
        ArrayAdapter adapter = new ArrayAdapter(this, R.layout.my_spinner_item, varietyList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        varietySpinner.setAdapter(adapter);
        //设置默认的采收品种
        varietySpinner.setSelection(varietyPosition);
        varietySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                variety=varietyList.get(i);

                varietyCode=varietyCodeList.get(i);
                varietyCodeTextView.setText(varietyCode);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }

    //打包规格的spinner
    public void packingSpecificationsSpinner() {
        ArrayAdapter adapter = new ArrayAdapter(this, R.layout.my_spinner_item, packingSpecificationsList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        packingSpecificationsSpinner.setAdapter(adapter);
        //设置默认的打包规格
        packingSpecificationsSpinner.setSelection(packingSpecificationsPosition);
        packingSpecificationsSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                packingSpecifications=packingSpecificationsList.get(i);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }

    //花杆长度的spinner
    public void flowerPoleLengthSpinner() {
        ArrayAdapter adapter = new ArrayAdapter(this, R.layout.my_spinner_item, flowerPoleLengthList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        flowerPoleLengthSpinner.setAdapter(adapter);
        //设置默认的花杆长度
        flowerPoleLengthSpinner.setSelection(flowerPoleLengthPosition);
        flowerPoleLengthSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                flowerPoleLength=flowerPoleLengthList.get(i);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }

    //等级的spinner
    public void classesSpinner() {
        ArrayAdapter adapter = new ArrayAdapter(this, R.layout.my_spinner_item, classesList);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        classesSpinner.setAdapter(adapter);
        //设置默认的等级
        classesSpinner.setSelection(classesPosition);
        classesSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                classes = classesList.get(i);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
            }
        });
    }

    // 获取当前日期
    public void getDate() {
        Calendar calendar = Calendar.getInstance();
        mYear = calendar.get(Calendar.YEAR);
        mMonth = calendar.get(Calendar.MONTH);
        mDay = calendar.get(Calendar.DAY_OF_MONTH);
    }

    // 保存编辑的毛产品信息
    public void save() {
        progressBar.setVisibility(View.VISIBLE);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("id",deliverVariety.getId());
        map.put("classes",classes);//等级
        map.put("flowerPoleLength",flowerPoleLength);//花杆长度
        map.put("number",number);//数量
        map.put("packingSpecifications",packingSpecifications);//打包规格
        map.put("variety",variety);//品种
        String requestJsonString = JSON.toJSONString(map);

        String url = IPConfig.baseUrl + "/flower/flowerOutorderinfo/edit";
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(mediaType, requestJsonString);
        OkHttpUtils
                .put()
                .addHeader("X-Access-Token", token)
                .url(url)
                .requestBody(body)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progressBar.setVisibility(View.GONE);
                        Toast.makeText(DeliverVarietyDetailActivity.this, "Token失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(DeliverVarietyDetailActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        progressBar.setVisibility(View.GONE);
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            AlertDialog alertDialog = new AlertDialog.Builder(DeliverVarietyDetailActivity.this).create();
                            alertDialog.setMessage("出库品种信息修改成功");
                            alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent intent = new Intent(DeliverVarietyDetailActivity.this, DeliverDetailActivity.class);
                                    intent.putExtra("deliverDetail", (Serializable) deliver);
                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
                                    startActivity(intent);
                                }
                            });
                            alertDialog.setCanceledOnTouchOutside(false);
                            alertDialog.show();
                        }
                    }
                });
    }

    // 删除出库信息
    public void delete() {
        progressBar.setVisibility(View.VISIBLE);
        String url = IPConfig.baseUrl + "/flower/flowerOutorderinfo/delete/?id="+deliverVariety.getId();
        MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
        OkHttpUtils
                .delete()
                .addHeader("X-Access-Token", token)
                .url(url)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        progressBar.setVisibility(View.GONE);
                        Toast.makeText(DeliverVarietyDetailActivity.this, "Token失效，请重新登录", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent(DeliverVarietyDetailActivity.this, LoginActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        progressBar.setVisibility(View.GONE);
                        boolean success = Boolean.parseBoolean(JSON.parseObject(response).getString("success"));
                        if (success) {
                            AlertDialog alertDialog = new AlertDialog.Builder(DeliverVarietyDetailActivity.this).create();
                            alertDialog.setMessage("出库品种信息删除成功");
                            alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Intent intent = new Intent(DeliverVarietyDetailActivity.this, DeliverDetailActivity.class);
                                    intent.putExtra("deliverDetail", (Serializable) deliver);
                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
                                    startActivity(intent);
                                }
                            });
                            alertDialog.setCanceledOnTouchOutside(false);
                            alertDialog.show();
                        }
                    }
                });
    }
}